package farmaciaweb.com.br.dao.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import farmaciaweb.com.br.dao.SubstanciaDAO;
import farmaciaweb.com.br.entity.Substancia;
import farmaciaweb.com.br.util.JPAUtil;

public class SubstanciaDAOImpl implements SubstanciaDAO{

	private static final long serialVersionUID = -4104167032461142552L;
	
private EntityManager em;
	

	
	@Override
	public Substancia saveAtomic(Substancia substancia) {
		Substancia substanciaSalva = null;
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			substanciaSalva = this.em.merge(substancia);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			return null;
		}	
		
		return substanciaSalva;	
	}
	
	@Override
	public void deleteAtomic(Substancia subs) {
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			this.em.remove(subs);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			e.getStackTrace();
		}	
		
	}
	
	public List<Substancia> pesquisarSubstancia(String desc){
		Map<String, Object> listaParams;
		listaParams = new HashMap<String, Object>();
		listaParams.put("desc", desc);		
		return JPAUtil.findByNamedQueryAndNamedParams("bd_farmaciaweb.consultaSubstancia", listaParams);
	}
	
	public Substancia findById(int id){
		Substancia t = new Substancia();
		t = em.find(Substancia.class, id);
		return t;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Substancia> findAll() {
		this.em = JPAUtil.getEntityManger();
		Query query = this.em.createQuery("SELECT e FROM Substancia e ORDER BY e.descricao");
		return query.getResultList();
	}
	
	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

}
